import { useState, useEffect } from 'react';
import ChoseBox from '../ChoseBox';

const monthArr = Array.from({ length: 31 }, (v, k) => k + 1);

const MonthPicker = (props: { value: any; onChange: any }) => {
  const { value, onChange } = props;
  const [checkedArr, setCheckedArr] = useState<number[]>(value);

  const handleClick = (idx: number) => {
    const retArr = [...checkedArr];
    const index: number = retArr.findIndex((o) => o === idx);
    if (index > -1) {
      retArr.splice(index, 1);
    } else {
      retArr.push(idx);
    }
    onChange && onChange(retArr);
  };

  const checkAll = () => {
    onChange && onChange(monthArr);
  };

  useEffect(() => {
    setCheckedArr(value);
  }, [value]);

  return (
    <>
      {monthArr.map((obj, idx) => (
        <span key={obj} onClick={() => handleClick(idx + 1)}>
          <ChoseBox name={`${obj}号`} checked={(checkedArr || []).includes(idx + 1)} />
        </span>
      ))}
      <span onClick={checkAll}>
        <ChoseBox name="全部" color="#3546d0" />
      </span>
    </>
  );
};

export default MonthPicker;
